<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    // generator  可以让循环或函数停止
    // function loop() {
    //   for (var i = 0; i < 10; i++) {
    //     // if (i % 2 == 0) {
    //     //   continue
    //     // }
    //     if (i == 3) {
    //       break;
    //     }
    //     console.log(i)
    //   }
    // }
    // loop()
    // 1 写法的区别 函数名中间加* 
    // 2.generator 函数结合yeild 使用
    function* loop() {
      console.log("函数开始")
      for (var i = 0; i < 10; i++) {
        yield console.log(i)// 2 yield 当generator函数执行到yield 程序会停止
      }
    }
    // generator 函数使用前 先调用得到返回值
    var l = loop();
    console.log(l)
    //4.让generator 函数继续执行的方法是next()
    l.next()
    l.next()
    l.next()
    l.next()
    //2-------------------------------------------------
    function* gen() {
      let val;
      console.log("开始")
      val = yield 1 + 1;
      console.log(val)
    }
    // yield 后无法得到返回值 
    //想得到yeild后的值
    var g = gen();
    // g.next==={done:true,value:2}//done 代表generator是否执行完毕 true执行完毕
    console.log(g.next()) //g.next().value 是得到yeild后返回值
    console.log(g.next())

    // 三  yeild后的*  是循环yeild 后的值
    function* gen2() {
      let val;
      val = yield* [1, 2, 3]
      console.log(val)
    }
    var g2 = gen2();
    console.log(g2.next())
    // g.return()  //手动停止generator
    g2.return(88)
    console.log(g2.next())
    console.log(g2.next())
    console.log(g2.next())

    function* gen3() {
      while (true) {
        try {
          yield 1
        } catch (e) {//捕获错误
          console.log(e.message)
          break;
        }
      }
    }
    var g3 = gen3();
    console.log(g3.next())
    console.log(g3.next())
    console.log(g3.next())
    // 抛出异常到generator
    g3.throw(new Error("这是个死循环"))
    console.log(g3.next())
    console.log(g3.next())
    console.log(g3.next())
  </script>
</body>

</html>